package com.jiyinit.web.core.common.util;

import com.jiyinit.core.framework.base.util.LogUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 加载配置文件
 * @author zhaolaiwei
 * @version 1.0
 * @date 2017/4/12 14:33
 * @since 1.0
 */
public class GlobalsUtils {

    /**
     * 日志文件
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(GlobalsUtils.class);

    /**
     * application.properties文件路径
     */
    private static final String APPLICATION_PROPERTIES_PATH = "/application.properties";

    /**
     * 存放当前配置文件中的键值对,放入内存
     */
    private static Map<String, String> configFileNamesMap = new ConcurrentHashMap<String, String>();

    static {
        try {
            loadConfig(APPLICATION_PROPERTIES_PATH);
        } catch (IOException e) {
            LogUtil.error(LOGGER, "加载配置文件失败, error:{}", e);
        }
    }

    /**
     * 配置文件键值加载到内存
     *
     * @param name
     * @throws IOException
     */
    private static void loadConfig(String name) throws IOException {
        try {
            String path = Thread.currentThread().getContextClassLoader().getResource(name).getPath();
            LogUtil.info(LOGGER, "当前加载配置文件路径为path={}", path);
            InputStream in = new BufferedInputStream(new FileInputStream(path));
            if (in != null) {
                Properties p = new Properties();
                p.load(in);
                Set<Object> keys = p.keySet();
                if (keys != null && keys.size() > 0) {
                    for (Object object : keys) {
                        String key = (String) object;
                        if (configFileNamesMap == null) configFileNamesMap = new LinkedHashMap<String, String>();
                        configFileNamesMap.put(key, p.getProperty(key));
                    }
                }
            }
            LogUtil.info(LOGGER, "当前内存的configFileNamesMap={}", configFileNamesMap.toString());
        } catch (Exception e) {
            LogUtil.error(LOGGER, "加载配置文件失败, error:{}", e);
        }
    }

    /**
     * 获取key值
     * @param paramName
     * @return
     */
    public static String getValue(String paramName) {
        return configFileNamesMap.get(paramName);
    }

}
